package com.app.micaihu.view.lunch;

import android.Manifest;
import android.annotation.SuppressLint;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.graphics.drawable.Animatable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.text.Html;
import android.text.TextUtils;
import android.view.KeyEvent;
import android.view.View;
import android.widget.FrameLayout;
import android.widget.TextView;

import androidx.annotation.MainThread;
import androidx.annotation.NonNull;
import androidx.lifecycle.LiveData;
import androidx.lifecycle.Observer;

import com.android.volley.VolleyError;
import com.app.base.BaseActivity;
import com.app.micaihu.R;
import com.app.micaihu.ad.AdConfig;
import com.app.micaihu.ad.toutiao.TTAdManagerHolder;
import com.app.micaihu.ad.toutiao.ToutiaoAdManager;
import com.app.micaihu.app.AppApplication;
import com.app.micaihu.base.bean.DataBean;
import com.app.micaihu.bean.ad.NativeAd;
import com.app.micaihu.bean.config.AppControl;
import com.app.micaihu.bean.config.Channel;
import com.app.micaihu.bean.news.NewsEntity;
import com.app.micaihu.configure.Config;
import com.app.micaihu.configure.ConfigKeyConstant;
import com.app.micaihu.configure.TypeConstant;
import com.app.micaihu.configure.URIContant;
import com.app.micaihu.configure.UmEventId;
import com.app.micaihu.configure.UserConfigTools;
import com.app.micaihu.custom.components.ParamMap;
import com.app.micaihu.custom.components.downandupload.DownloadUtils;
import com.app.micaihu.custom.view.CustomImageView;
import com.app.micaihu.db.NewsDBUtil;
import com.app.micaihu.listener.HttpListener;
import com.app.micaihu.manager.AppConfigManager;
import com.app.micaihu.manager.ServiceDeliveryManager;
import com.app.micaihu.service.DownLoadService;
import com.app.micaihu.utils.AppShareUtils;
import com.app.micaihu.utils.HttpUtils;
import com.app.micaihu.utils.LiveDataBus;
import com.app.micaihu.utils.MobclickAgentUtils;
import com.app.micaihu.videoplayer.JCVideoPlayer;
import com.app.micaihu.view.lunch.dialog.ClosePermissionDialog;
import com.app.micaihu.view.lunch.dialog.ConfirmPermissionDialog;
import com.app.micaihu.view.lunch.dialog.FirstPermissionDialog;
import com.app.micaihu.view.main.MainActivity;
import com.app.micaihu.view.main.game.GameDownloadActivity;
import com.app.micaihu.view.user.userinfo.activity.WebActivity;
import com.app.okhttplib.OkHttpUtil;
import com.app.okhttplib.annotation.DownloadStatus;
import com.app.okhttplib.bean.DownloadFileInfo;
import com.app.utils.util.AppTools;
import com.app.utils.util.DateUtils;
import com.app.utils.util.StringUtils;
import com.app.utils.util.ToastUtils;
import com.app.utils.util.ViewSizeUtils;
import com.app.utils.util.image.LoadImageUtils;
import com.baidu.mobstat.StatService;
import com.blankj.utilcode.constant.PermissionConstants;
import com.blankj.utilcode.util.ActivityUtils;
import com.blankj.utilcode.util.AppUtils;
import com.blankj.utilcode.util.BarUtils;
import com.blankj.utilcode.util.CollectionUtils;
import com.blankj.utilcode.util.GsonUtils;
import com.blankj.utilcode.util.LogUtils;
import com.blankj.utilcode.util.PermissionUtils;
import com.blankj.utilcode.util.SPUtils;
import com.blankj.utilcode.util.ScreenUtils;
import com.blankj.utilcode.util.SizeUtils;
import com.blankj.utilcode.util.UtilsTransActivity;
import com.bytedance.sdk.openadsdk.AdSlot;
import com.bytedance.sdk.openadsdk.TTAdNative;
import com.bytedance.sdk.openadsdk.TTSplashAd;
import com.facebook.drawee.controller.ControllerListener;
import com.facebook.imagepipeline.image.ImageInfo;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.umeng.analytics.MobclickAgent;

import org.jetbrains.annotations.NotNull;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.File;
import java.lang.ref.WeakReference;
import java.util.HashMap;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import static com.app.micaihu.ad.AdConfig.AD_TYPE_TOUTIAO;

/**
 * 软件启动页面
 *
 * @author linkai
 */
public class LunchActivity extends BaseActivity {

    private CustomImageView appstartimg;
    private View bottomLayout;//底部横幅
    private FrameLayout topLayout;//上部容器
    private TextView skipView;//跳过
    private View skipProgess;

    private boolean isAdLoad;//是否加载广告
    private Timer timer;//跳过计时器
    private int adTime = 3;//进入主页面计时时间,默认3秒
    private boolean isBotomShow;//是否显示底部
    private long startTime;//开始时间

    private FirstPermissionDialog firstPermissionDialog;

    private boolean isjump = false;


    private static void handleMsg(Activity activity, Message msg) {
        LunchActivity lunchActivity = null;
        if (activity instanceof LunchActivity) {
            lunchActivity = (LunchActivity) activity;
        }
        if (msg != null && lunchActivity != null) {
            switch (msg.what) {
                case -1:
                    activity.startActivity(new Intent(lunchActivity, MainActivity.class));
                    break;
                case 0://显示topLayout
                    if (lunchActivity.isBotomShow && lunchActivity.topLayout != null) {
                        lunchActivity.topLayout.setBackgroundColor(lunchActivity.getResources().getColor(R.color.common_font_color_6));
                        lunchActivity.appstartimg.setVisibility(View.GONE);
                    }
                    break;
                case 2://倒计时
                    //如果跳转过广告则不再执行跳转主页面
                    lunchActivity.adTime--;
                    lunchActivity.skipView.setText(Html.fromHtml("跳过\n" + "<font color='#E55D5D'>" + lunchActivity.adTime + "</font>" + "s"));
                    if (lunchActivity.adTime <= 0) {
                        //退出循环
                        if (lunchActivity.timer == null) {
                            lunchActivity.timer.cancel();
                            lunchActivity.timer = null;
                        }
                        //跳转页面
                        lunchActivity.redirectToActivity();
                    }
                    break;
            }
        }
    }

    private boolean isToOtherPager;
    private MyHandler handler = new MyHandler(this);

    @Override
    protected void initBar(boolean initBar) {
        super.initBar(false);
        BarUtils.transparentStatusBar(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        // 百度统计
        StatService.onResume(this);
        // 友盟统计
        MobclickAgent.onResume(this);
        if (isToOtherPager) {
            isToOtherPager = false;
            redirectToMain();
        }
    }

    @Override
    protected void onPause() {
        super.onPause();
        // 百度统计
        StatService.onPause(this);
        // 友盟统计
        MobclickAgent.onPause(this);
        isToOtherPager = true;
        if (isToOtherPager) {
            close();
        }
        com.blankj.utilcode.util.LogUtils.e("-onPause->" + isToOtherPager);
    }


    private void close() {
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            timer.cancel();
        }
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_lunch;
    }

    @Override
    protected void setData() {
        boolean readPhoneState = PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE);
        boolean writeStorage = PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
        Bundle bundle1 = new Bundle();
        bundle1.putBoolean(Config.Extra.phoneState, readPhoneState);
        bundle1.putBoolean(Config.Extra.writeStorage, writeStorage);
        firstPermissionDialog = FirstPermissionDialog.getFirstDialog(bundle1);
        if (!readPhoneState || !writeStorage) {
            firstPermissionDialog.show(getSupportFragmentManager());
        } else {
            init();
        }
        firstPermissionDialog.setOnOpenClick(new FirstPermissionDialog.OnOpenClick() {
            @Override
            public void onOpenClick() {
                firstPermissionDialog.dismiss();
                getPermission();
            }

            @Override
            public void onCloseClick() {
                ClosePermissionDialog closePermissionDialog = ClosePermissionDialog.getCloseDialog();
                closePermissionDialog.show(getSupportFragmentManager());
                closePermissionDialog.setOnOpenClick(new ClosePermissionDialog.OnOpenClick() {
                    @Override
                    public void onCancelClick() {
                        firstPermissionDialog.show(getSupportFragmentManager());
                    }

                    @Override
                    public void onOkClick() {
                        AppUtils.exitApp();
                    }
                });
            }
        });
        loadChannel();
    }

    @Override
    protected void addListeners() {

    }

    private void init() {
        if (handler != null) {
            handler.sendEmptyMessageDelayed(-1, 7000);
        }
        startTime = System.currentTimeMillis();
        // 初始化控件
        initView();
        // 拉取服务器开屏配置
        configScreenImg();
        //开屏广告
        configSpreadAD();
        //拉取活动
        ServiceDeliveryManager.getSingleton().requestActivity();
        //清理数据库
        clearDB();
        //配置 oneApm性能监控
        configAPM();
        // 跳转主界面
        redirectToMain();
    }


    /**
     * 初始化控件
     */
    private void initView() {
        this.appstartimg = (CustomImageView) findViewById(R.id.app_start_img);
        this.bottomLayout = findViewById(R.id.bottom_img_layout);
        this.topLayout = (FrameLayout) findViewById(R.id.start_img_layout);
        this.skipProgess = findViewById(R.id.pb_loading_progress);
        this.skipView = (TextView) findViewById(R.id.tv_tiaoguo);
    }

    @SuppressLint("WrongConstant")
    private void getPermission() {
        PermissionUtils.permission(PermissionConstants.STORAGE, Manifest.permission.READ_PHONE_STATE)
                .rationale(new PermissionUtils.OnRationaleListener() {
                    @Override
                    public void rationale(@NotNull UtilsTransActivity activity, @NotNull ShouldRequest shouldRequest) {
                        shouldRequest.again(true);
                    }
                })
                .callback(new PermissionUtils.FullCallback() {
                    @Override
                    public void onGranted(@NotNull List<String> permissionsGranted) {
                        isToOtherPager = false;
                        if (permissionsGranted.contains(Manifest.permission.READ_PHONE_STATE)
                                && permissionsGranted.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                            init();
                        }
                    }

                    @Override
                    public void onDenied(@NotNull List<String> permissionsDeniedForever, @NotNull List<String> permissionsDenied) {
                        if (permissionsDeniedForever.isEmpty()) {
                            boolean readPhoneState = PermissionUtils.isGranted(Manifest.permission.READ_PHONE_STATE);
                            boolean writeStorage = PermissionUtils.isGranted(Manifest.permission.WRITE_EXTERNAL_STORAGE);
                            Bundle bundle1 = new Bundle();
                            bundle1.putBoolean(Config.Extra.phoneState, readPhoneState);
                            bundle1.putBoolean(Config.Extra.writeStorage, writeStorage);
                            firstPermissionDialog.setArguments(bundle1);
                            firstPermissionDialog.show(getSupportFragmentManager());
                        } else {
                            Bundle bundle2 = new Bundle();
                            bundle2.putBoolean(Config.Extra.phoneState, permissionsDenied.contains(Manifest.permission.READ_PHONE_STATE));
                            bundle2.putBoolean(Config.Extra.writeStorage, permissionsDenied.contains(Manifest.permission.WRITE_EXTERNAL_STORAGE));
                            ConfirmPermissionDialog confirmPermissionDialog = ConfirmPermissionDialog.getFirstDialog(bundle2);
                            confirmPermissionDialog.show(getSupportFragmentManager());
                            confirmPermissionDialog.setOnOpenClick(new ConfirmPermissionDialog.OnOpenClick() {
                                @Override
                                public void onOpenClick() {
                                    PermissionUtils.launchAppDetailsSettings();
                                    AppUtils.exitApp();
                                }

                                @Override
                                public void onCloseClick() {
                                    ClosePermissionDialog closePermissionDialog = ClosePermissionDialog.getCloseDialog();
                                    closePermissionDialog.show(getSupportFragmentManager());
                                    closePermissionDialog.setOnOpenClick(new ClosePermissionDialog.OnOpenClick() {
                                        @Override
                                        public void onCancelClick() {
                                            firstPermissionDialog.show(getSupportFragmentManager());
                                        }

                                        @Override
                                        public void onOkClick() {
                                            AppUtils.exitApp();
                                        }
                                    });
                                    firstPermissionDialog.dismiss();
                                }
                            });
                        }
                    }
                }).request();
    }

    /**
     * 配置即将加载的开屏广告
     */
    private void configSpreadAD() {
        //获取底部的配置
        isBotomShow = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.spreadBottomShow, false);
        //当天第一次打开不显示广告
        String currentTime = DateUtils.getCurrentTime("dd");
        String oldTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.openAPPFirst, "");
        if (!TextUtils.equals(currentTime, oldTime)) {
            //如果不相同 则说明不是同一天 则不走广告逻辑
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.openAPPFirst, currentTime);

            //新的一天.将播放广告的次数清0
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.adPlayed, "");

            return;
        }
        //加载开屏
        String adProly = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.spreadAdProbability, "");
        double random = Math.random();//生成随机数
        if (TextUtils.isEmpty(adProly) || random > StringUtils.toFloat(adProly, 0f)) {
            //配置为空或者几率大于服务器配置则不再显示广告
            return;
        }
        //获取服务器配置的开屏广告 json配置
        String adJson = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.lunchAdStr, "");
        if (TextUtils.isEmpty(adJson)) {
            return;
        }
        //显示广告逻辑
        final NativeAd nativeAd = GsonUtils.fromJson(adJson, NativeAd.class);
        if (nativeAd == null || TextUtils.isEmpty(nativeAd.getAdId())) {
            return;
        }
        //广告允许加载标识
        isAdLoad = true;
        //显示底部白色图片
        if (isBotomShow) {
            this.bottomLayout.setVisibility(View.VISIBLE);
        } else {
            this.bottomLayout.setVisibility(View.GONE);
        }
        //如果有广告该页面重新设置倒计时时间
        adTime = 5;
        final boolean[] ispipei = {false};
        if (TextUtils.equals(AdConfig.AD_TYPE_H5, nativeAd.getAdType())
                && nativeAd.getThumbList() != null && nativeAd.getThumbList().length > 0) {
            //h5广告
            LoadImageUtils.getInstance().loadImage(appstartimg, nativeAd.getThumbList()[0], new ControllerListener<ImageInfo>() {
                @Override
                public void onSubmit(String id, Object callerContext) {

                }

                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {
                    if (bottomLayout == null || LunchActivity.this.isFinishing()) {
                        return;
                    }
                    //显示底部白色图片
                    if (isBotomShow) {
                        bottomLayout.setVisibility(View.VISIBLE);
                        topLayout.setBackgroundColor(getResources().getColor(R.color.common_font_color_6));
                    } else {
                        bottomLayout.setVisibility(View.GONE);
                    }
//                    showTopLayout();
                    if (skipView != null) {
                        skipView.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

                }

                @Override
                public void onIntermediateImageFailed(String id, Throwable throwable) {

                }

                @Override
                public void onFailure(String id, Throwable throwable) {

                }

                @Override
                public void onRelease(String id) {

                }
            });
            appstartimg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(LunchActivity.this, WebActivity.class);
                    intent.putExtra("url", nativeAd.getJumpUrl());
                    intent.putExtra("isMain", "1");
                    startActivity(intent);
                    handler.removeCallbacksAndMessages(null);
                    timer.cancel();
                    finish();
                }
            });
            ispipei[0] = true;
        } else if (TextUtils.equals(AdConfig.AD_TYPE_GAME, nativeAd.getAdType())
                && nativeAd.getThumbList() != null && nativeAd.getThumbList().length > 0) {
            MobclickAgentUtils.event(UmEventId.game_exposed, UmEventId.INSTANCE.getScreen());
            LoadImageUtils.getInstance().loadImage(appstartimg, nativeAd.getThumbList()[0], new ControllerListener<ImageInfo>() {
                @Override
                public void onSubmit(String id, Object callerContext) {

                }

                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {

                    if (bottomLayout == null || LunchActivity.this.isFinishing()) {
                        return;
                    }

                    //显示底部白色图片
                    if (isBotomShow) {
                        bottomLayout.setVisibility(View.VISIBLE);

                    } else {
                        bottomLayout.setVisibility(View.GONE);
                    }
                    if (skipView != null) {
                        skipView.setVisibility(View.VISIBLE);
                    }
                }

                @Override
                public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

                }

                @Override
                public void onIntermediateImageFailed(String id, Throwable throwable) {

                }

                @Override
                public void onFailure(String id, Throwable throwable) {

                }

                @Override
                public void onRelease(String id) {

                }
            });
            appstartimg.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    MobclickAgentUtils.event(UmEventId.game_click, UmEventId.INSTANCE.getScreen());
                    MobclickAgentUtils.event(UmEventId.game_download, UmEventId.INSTANCE.getScreen());
                    boolean appInstalled = AppUtils.isAppInstalled(nativeAd.getPackageName());
                    if (appInstalled) {
//                        com.app.okhttplib.util.AppUtils.startUpApp(getThisContext(), nativeAd.getIPackageName());
                        ToastUtils.makeText("已下载");
                    } else {
                        //插入到数据库中
                        File unInstallFile = new File(DownloadUtils.DOWNLOAD_FILEDIR, nativeAd.getIPath() + ".apk");
                        if (unInstallFile.exists() && unInstallFile.isFile()) {//安装游戏
//                            com.app.okhttplib.util.AppUtils.installAPP(getThisContext(), unInstallFile);
                            ToastUtils.makeText("已下载");
                        } else {
                            DownloadFileInfo downloadFileInfo = DownloadUtils.getSingleton().getDownloadFileInfo(OkHttpUtil.getTag(nativeAd.getIUrl()));
                            if (downloadFileInfo == null) {
                                ToastUtils.makeText("开始下载");
                                DownloadUtils.getSingleton().down(nativeAd.getIUrl(), nativeAd.getIPath(), nativeAd, UmEventId.INSTANCE.getScreen());
                                GameDownloadActivity.insertGame(nativeAd.getIGameId(), nativeAd.getITitle(), nativeAd.getIUrl(), nativeAd.getIAppIcon(),
                                        nativeAd.getIGameSummary(), nativeAd.getIPackageName(), nativeAd.getIPath(), nativeAd.getISize());
                            } else {
                                String downloadStatus = downloadFileInfo.getDownloadStatus();
                                if (!DownloadStatus.DOWNLOADING.equals(downloadStatus)) {
                                    ToastUtils.makeText("开始下载");
                                    DownloadUtils.getSingleton().down(nativeAd.getIUrl(), nativeAd.getIPath(), nativeAd, UmEventId.INSTANCE.getScreen());
                                    GameDownloadActivity.insertGame(nativeAd.getIGameId(), nativeAd.getITitle(), nativeAd.getIUrl(), nativeAd.getIAppIcon(),
                                            nativeAd.getIGameSummary(), nativeAd.getIPackageName(), nativeAd.getIPath(), nativeAd.getISize());
                                }
                            }
                        }
                    }
                }
            });
            ispipei[0] = true;
        } else if (TextUtils.equals(AdConfig.AD_TYPE_TOUTIAO, nativeAd.getAdType())) {
            bottomLayout.setVisibility(View.GONE);
            LogUtils.e(getClassTag(), "----------??" + ScreenUtils.getScreenHeight());
            ispipei[0] = true;
            TTAdNative mTTAdNative = TTAdManagerHolder.get().createAdNative(getThisContext());
            //开屏广告参数
            AdSlot adSlot = new AdSlot.Builder()
                    .setCodeId(nativeAd.getAdId())
                    .setSupportDeepLink(true)
                    .setExpressViewAcceptedSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                    .setImageAcceptedSize(ScreenUtils.getScreenWidth(), ScreenUtils.getScreenHeight())
                    .build();
            //调用开屏广告异步请求接口
            mTTAdNative.loadSplashAd(adSlot, new TTAdNative.SplashAdListener() {
                @Override
                @MainThread
                public void onError(int code, String message) {
                    LogUtils.e(getClassTag(), "toutiao error->" + message);
//                    HashMap<String, String> map = AdMapUtils.getPositionMap();
//                    map.put(AdMapUtils.adPositionSplash + "onError", nativeAd.getAdId());
//                    map.put(AdMapUtils.adPositionSplash + "errorMsg", message);
//                    map.put(AdMapUtils.adPositionSplash + "errorCode", code + "");
//                    MobclickAgentUtils.event(Config.EventId.toutiao_ad, map);
//                    if (listener != null) {
//                        listener.onADFail("code->" + code + " message->" + message);
//                    }
                }

                @Override
                @MainThread
                public void onTimeout() {
                    LogUtils.e(getClassTag(), "toutiao onTimeout->");
                }

                @Override
                @MainThread
                public void onSplashAdLoad(TTSplashAd ad) {
                    if (ad == null) {
                        return;
                    }
                    LogUtils.e(getClassTag(), "toutiao onSplashAdLoad->");
//                    HashMap<String, String> map = AdMapUtils.getPositionMap();
//                    map.put(AdMapUtils.adPositionSplash + AdMapUtils.adSuccessKey, nativeAd.getAdId());
//                    MobclickAgentUtils.event(Config.EventId.toutiao_ad, map);
                    View view1 = ad.getSplashView();
                    //把SplashView 添加到ViewGroup中
                    topLayout.addView(view1);

                    if (skipView != null) {
                        skipView.setVisibility(View.VISIBLE);
                    }
                    //设置不开启开屏广告倒计时功能以及不显示跳过按钮
                    ad.setNotAllowSdkCountdown();

                    //设置SplashView的交互监听器
                    ad.setSplashInteractionListener(new TTSplashAd.AdInteractionListener() {
                        @Override
                        public void onAdClicked(View view, int type) {
//                            if (listener != null) {
//                                listener.onADClicked();
//                            }
                        }

                        @Override
                        public void onAdShow(View view, int type) {
//                            if (listener != null) {
//                                listener.onADPresent();
//                            }
                        }

                        @Override
                        public void onAdSkip() {
                        }

                        @Override
                        public void onAdTimeOver() {
                        }
                    });
                }
            }, 5000);
        }

        if (ispipei[0]) {
            skipView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    if (skipView != null) {
                        skipView.setVisibility(View.GONE);
                    }
                    if (skipProgess != null) {
                        skipProgess.setVisibility(View.VISIBLE);
                    }
//                    isAdTiaozhuan = true;
                    redirectToActivity();
                }
            });
        }
    }

    /**
     * 展示上方图片
     */
    private void showTopLayout() {
        if (LunchActivity.this.isFinishing()) {
            return;
        }
        if (skipView != null) {
            skipView.setVisibility(View.VISIBLE);
        }
        long endTime = System.currentTimeMillis();
        if ((endTime - startTime) >= 1000 && topLayout != null) {
            topLayout.setVisibility(View.VISIBLE);

            if (isBotomShow) {
                this.topLayout.setBackgroundColor(getResources().getColor(R.color.common_font_color_6));
                appstartimg.setVisibility(View.GONE);
            }

        } else if (topLayout != null) {
            if (handler != null) {
                handler.sendEmptyMessageDelayed(0, 1000 - (endTime - startTime));
            }
        }
    }

    /**
     * 进行开屏配置
     */
    private void configScreenImg() {


        ParamMap parms = new ParamMap();
        parms.putEncode("imei", AppTools.getIMEI());
        parms.putEncode("version", AppTools.getVersionName());
        parms.putEncode("type", "1");//1 安卓 2ios

        parms.putEncode("umengToken", AppConfigManager.getInstance().readConfig(UserConfigTools.UMENG_TOKEN, ""));
        parms.putEncode("xiaomiToken", AppConfigManager.getInstance().readConfig(UserConfigTools.XIAOMI_REGID, ""));
        parms.putEncode("spushToken", AppConfigManager.getInstance().readConfig(UserConfigTools.GT_CID, ""));//个推cid
        parms.putEncode("terminal", AppTools.getAerminal());

//        LogUtils.i("小米id----" + AppConfigManager.getInstance().readConfig(UserConfigTools.XIAOMI_REGID, ""));

        HttpUtils.ParmsMapMD5(parms);
        HttpListener<DataBean<AppControl>> httpListener = new HttpListener<DataBean<AppControl>>() {
            @Override
            public void onError(VolleyError error) {
                setStartImg(null);//设置开屏
            }

            @Override
            public void onSuccess(DataBean<AppControl> response) {
                if (response.noError() && response.getData() != null) {
                    AppControl appControl = response.getData();
                    //设置开屏
                    setStartImg(appControl.getAppStartImg());
//                    //检查更新新闻栏目
//                    checkUpdateChannel(appControl.getAppChannelData());
                    //检查开屏广告配置
//                    checkSpreadAD(appControl.getAdUptime(), appControl.adListToJson());
                    List<NativeAd> adList = appControl.getAdList();
                    if (CollectionUtils.isNotEmpty(adList)) {
                        checkSpreadAD(appControl.getAdUptime(), GsonUtils.toJson(adList.get(0)));
                    }
                    //存储其他配置
                    SharedPreferences sharedPreferences = AppConfigManager.getInstance().getConfigSP();
                    SharedPreferences.Editor editor = sharedPreferences.edit();

                    //官方邀请码
                    editor.putString(ConfigKeyConstant.officialInviteCode, appControl.getOfficialInviteCode());

                    //设置游戏的贴片广告播放次数
                    editor.putString(ConfigKeyConstant.adPlayNum, appControl.getAdPlayNum());

                    //首页默认选中项
                    editor.putString(ConfigKeyConstant.selectCate, appControl.getSelectCate());


                    //内页显示展开全文的按钮_默认不显示
                    editor.putBoolean(ConfigKeyConstant.showDetail, appControl.getShowDetail());

                    //存储底部是否显示的配置
                    editor.putBoolean(ConfigKeyConstant.spreadBottomShow, appControl.getShowBottomImg());
                    //存储广告出现的几率配置
                    editor.putString(ConfigKeyConstant.spreadAdProbability, appControl.getAdRatio());
                    //存储视频是否自动播放
                    editor.putBoolean(ConfigKeyConstant.autoPaly, appControl.getAutoPlayVideo());

                    SPUtils.getInstance().put(ConfigKeyConstant.popupStatus, appControl.getPopupStatus());
                    SPUtils.getInstance().put(ConfigKeyConstant.popupImg, appControl.getPopupImg());
                    SPUtils.getInstance().put(ConfigKeyConstant.popupUrl, appControl.getPopupUrl());

                    AppControl.ShowWakeScreen showWakeScreen = appControl.getShowWakeScreen();

                    if (showWakeScreen != null) {
                        editor.putBoolean(ConfigKeyConstant.isShowLunch, showWakeScreen.getWakeSwitch() == 1);//后台沉睡再次启动切换到app是否显示开屏画面 1是 0否
                        //应用切到后台 显示启动页的时间
                        editor.putInt(ConfigKeyConstant.backgroundTime, showWakeScreen.getWakeTime() * 1000);
                        //应用切到后台 每天展示的次数
                        editor.putInt(ConfigKeyConstant.displayServiceTimes, showWakeScreen.getShowNum());
                    }
                    AppControl.Mission mission = appControl.getMission();
                    if (mission != null) {
                        SPUtils.getInstance().put(ConfigKeyConstant.mission, GsonUtils.toJson(mission));
                    }
                    SPUtils.getInstance().put(ConfigKeyConstant.indexButtonSwitch, "1".equals(appControl.getIndexButtonSwitch()));
                    SPUtils.getInstance().put(ConfigKeyConstant.forceLogin, "1".equals(appControl.getForceLogin()));
                    String currentTime = DateUtils.getCurrentTime("yyyy-MM-dd");
                    String oldTime = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.APPFirstOpen, "");
                    if (!TextUtils.equals(currentTime, oldTime)) {
                        //如果不相同 则说明不是同一天 清空 当天本地展示启动页次数
                        editor.putInt(ConfigKeyConstant.displayLocalTimes, 0);
                        //如果不相同 则说明不是同一天 记录当前时间
                        editor.putString(ConfigKeyConstant.APPFirstOpen, currentTime);
                    }

                    UserConfigTools.isAutoPaly = appControl.getAutoPlayVideo();
                    List<NativeAd> preloadAdList = appControl.getPreloadAdList();

                    //存储预加载广告
                    if (preloadAdList != null && preloadAdList.size() > 0) {
                        for (NativeAd item : preloadAdList) {
                            if (AdConfig.AD_TYPE_TOUTIAO.equals(item.getAdType())) {
                                if (!TextUtils.isEmpty(item.getAdId())) {
                                    ToutiaoAdManager.getInstance().putAd(item);
                                }
                            }
                        }
                    } else {
                        editor.putString(ConfigKeyConstant.defaultADSmallid, "");
                        editor.putString(ConfigKeyConstant.defaultADBigid, "");
                        editor.putString(ConfigKeyConstant.defaultADThreeid, "");
                        editor.putString(ConfigKeyConstant.defaultGDTADBigid, "");
                        editor.putString(ConfigKeyConstant.defaultGDTADSmallid, "");
                        editor.putString(ConfigKeyConstant.defaultTouTiaoADSmallid, "");
                        editor.putString(ConfigKeyConstant.defaultTouTiaoADBigid, "");
                    }
                    //写入分享配置
                    if (appControl.getShareConfig() != null) {
                        AppShareUtils.appid = "appid";//初始化分享的id 保证每次打开app都是最新配置
                        editor.putString(ConfigKeyConstant.share_appid, appControl.getShareConfig().getAppId());
                        editor.putString(ConfigKeyConstant.share_packname, appControl.getShareConfig().getSharePackage());
                        editor.putString(ConfigKeyConstant.share_way, appControl.getShareConfig().getShareWay());
                    }
                    //存储话题重新拉取时间
                    editor.putString(ConfigKeyConstant.topicExpireTime, appControl.getTopicExpireTime());
                    //写入要闻推送的过期时间
                    editor.putString(ConfigKeyConstant.push_expireTime, appControl.getPushExpireTime());
                    //写入游戏按钮是否显示
                    editor.putBoolean(ConfigKeyConstant.isGameShow, appControl.getShowGame());
                    //首页游戏间隔时间
                    editor.putString("main_game_interval_time", appControl.getHitGap());

                    editor.putString(ConfigKeyConstant.showAgreement, appControl.getShowAgreement());
                    editor.putString(ConfigKeyConstant.userAgreementUrl, appControl.getUserAgreementUrl());
                    editor.putString(ConfigKeyConstant.privateAgreementUrl, appControl.getPrivateAgreementUrl());
                    editor.putString(ConfigKeyConstant.agreementUrl, appControl.getAgreementUrl());

                    editor.commit();
                    List<NativeAd> jiliAdInfo = appControl.getJiliAdInfo();
                    if (CollectionUtils.isNotEmpty(jiliAdInfo)) {
                        NativeAd nativeAd = jiliAdInfo.get(0);
                        if (nativeAd != null) {
                            SPUtils.getInstance().put(ConfigKeyConstant.signAdId, nativeAd.getAdId());
                        }
                    }
                    SPUtils.getInstance().put(ConfigKeyConstant.showSearchGame, appControl.getShowSearchGame());
                } else {
                    setStartImg(null);//设置开屏
                }

            }
        };
        HttpUtils.addPostRequest(URIContant.LUNCH, new TypeToken<DataBean<AppControl>>() {
        }.getType(), getClassTag(), parms, httpListener);

    }

    /**
     * 设置开屏图片
     * 注意:服务器配置 空字符串则不显示开屏图片
     */
    private void setStartImg(String startImgURL) {
        if (isAdLoad) {
            //如果当前正在加载广告则 不加载开屏图片
            return;
        }
        if (startImgURL == null) {
            //如果网址为null 说明访问网络失败 则读取本地的配置
            startImgURL = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.app_start_img, "");
        } else {
            //如果不为null 则存储网址
            AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.app_start_img, startImgURL);
        }
        if (TextUtils.isEmpty(startImgURL)) {
            return;
        }
        if (appstartimg != null) {
            LoadImageUtils.getInstance().loadImage(appstartimg, startImgURL, new ControllerListener<ImageInfo>() {
                @Override
                public void onSubmit(String id, Object callerContext) {

                }

                @Override
                public void onFinalImageSet(String id, ImageInfo imageInfo, Animatable animatable) {

                    if (bottomLayout == null || LunchActivity.this.isFinishing()) {
                        return;
                    }
                    //显示底部白色图片
                    if (isBotomShow) {
                        bottomLayout.setVisibility(View.VISIBLE);
                        topLayout.setBackgroundColor(getResources().getColor(R.color.common_font_color_6));
                    } else {
                        bottomLayout.setVisibility(View.GONE);
                    }

                }

                @Override
                public void onIntermediateImageSet(String id, ImageInfo imageInfo) {

                }

                @Override
                public void onIntermediateImageFailed(String id, Throwable throwable) {

                }

                @Override
                public void onFailure(String id, Throwable throwable) {

                }

                @Override
                public void onRelease(String id) {

                }
            });
        }
    }

    /**
     * 检查开屏广告配置
     *
     * @param uptime
     * @param adListStr
     */
    private void checkSpreadAD(String uptime, String adListStr) {
//        if (TextUtils.isEmpty(uptime)) {
//            return;
//        }
//        String localUpdateData = AppConfigManager.getInstance().readConfig(ConfigKeyConstant.spreadAdUptime, "");
//        if (TextUtils.equals(localUpdateData, uptime)) {
//            //如果配置一样则不做覆盖更新
//            return;
//        }
//        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.spreadAdUptime, uptime);
        AppConfigManager.getInstance().writeConfig(ConfigKeyConstant.lunchAdStr, adListStr);
    }

    private void loadChannel() {
        //更新栏目
        HttpListener<DataBean<List<Channel>>> httpListener = new HttpListener<DataBean<List<Channel>>>() {
            @Override
            public void onError(VolleyError error) {
            }

            @Override
            public void onSuccess(DataBean<List<Channel>> response) {
                if (response.noError()) {
                    SPUtils.getInstance().put(ConfigKeyConstant.channel, GsonUtils.toJson(response.getData()));
                }
            }
        };
        HttpUtils.addPostRequest(URIContant.channel, new TypeToken<DataBean<List<Channel>>>() {
        }.getType(), getClassTag(), null, httpListener);
    }

    /**
     * 配置oneAPM
     */
    private void configAPM() {
//        PerformanceConfiguration.getInstance().setEnableFps(true);
////        // 附加数据
////        HashMap<String, String> extraData = new HashMap<String, String>();
////        String imei = AppTools.getIMEI();
//////		extraData.put("tel", userTel);
////        extraData.put("userId", imei);
//////		extraData.put("email", "88888@qq.com");
//
//        ContextConfig config = new ContextConfig();
////        config.setSearchValue(imei); // 设置一个搜索值
////        config.setExtra(extraData);
//        try {
//            OneApmAgent.setContextConfig(config);
//            OneApmAgent.init(this.getApplicationContext()).setToken("82315A0A38F07B3FDE79281EC0255F3C99").start();
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
    }

    /**
     * 判断点赞数据文件是否过大，太大进行删除
     */
    private void clearDB() {
        new Thread() {
            public void run() {
                //清理数据库数据
                NewsDBUtil.getInstance().dbClear();
                //清理视频缓存数据
                JCVideoPlayer.clearSavedProgress(AppApplication.getInstance(), "");
            }
        }.start();
    }

    /**
     * 跳转主界面
     */
    private void redirectToMain() {

        timer = new Timer();
        skipView.setText(Html.fromHtml("跳过\n" + "<font color='#E55D5D'>" + adTime + "</font>" + "s"));
        //每隔1s就执行一次
        timer.schedule(new TimerTask() {

            @Override
            public void run() {
                if (handler != null) {
                    handler.sendEmptyMessage(2);
                }
            }
        }, 1000, 1000);
    }

    /**
     * 跳转主页面
     */
    private void redirectToActivity() {
        Intent intent = getIntent();
        boolean isToMain = true;
        if (intent != null) {
            String id = intent.getStringExtra(Config.Extra.PARAMETER1);
            String url = intent.getStringExtra("url");
            String serialId = intent.getStringExtra("serialId");
            String type = intent.getStringExtra(Config.Extra.PARAMETER2);
            NewsEntity newsEntity = new NewsEntity();
            newsEntity.setArticleId(id);
            newsEntity.setArticleType(type);
            newsEntity.setJumpUrl(url);
            newsEntity.setSerialId(serialId);
            isToMain = !TypeConstant.openTypeDetail(newsEntity, this, intent.getStringExtra(TypeConstant.PUSH_TYPE));
        }

        //如果跳转了内页则不再跳转主页面
        if (isToMain && !ActivityUtils.isActivityExistsInStack(MainActivity.class)) {
            startActivity(new Intent(LunchActivity.this, MainActivity.class));
            overridePendingTransition(R.anim.base_slide_right_in, R.anim.base_slide_remain);
        }
        finish();

    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        if (timer != null) {
            timer.cancel();
            timer = null;
        }
        if (handler != null) {
            handler.removeCallbacksAndMessages(null);
            handler = null;
        }
    }

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        return true;
    }


    private static class MyHandler extends Handler {
        WeakReference<Activity> reference;

        public MyHandler(Activity activity) {
            reference = new WeakReference<>(activity);
        }

        @Override
        public void handleMessage(@NonNull Message msg) {
            if (null != reference) {
                Activity activity = reference.get();
                if (null != activity) {
                    handleMsg(activity, msg);
                }
            }
        }
    }

}
